
var form = layui.form
// 获取友情链接列表

function load() {
  $(".layui-table tbody").empty();
  axios({
    headers: {
      Authorization: sessionStorage.getItem('mytoken')
    },
    url: "http://localhost:8888/admin/links",
    method: "GET"
  }).then(res => {
    res.data.data.forEach(function (val) {
      let arr = `<tr>
                          <th class="myid">${val.id}</th>
                          <th class="bg" ><img src="http://localhost:8888/uploads/${val.linkicon}" alt=""> </th>
                          <th>${val.linkname}</th>
                          <th>${val.linkurl}</th>
                          <th>${val.linkdesc}</th>
                       <th><span class="layui-badge layui-bg-green"><a href="javascript:;" data-ide=${val.id} class="bj" >编辑</a></span><span class="layui-badge"><a data-id=${val.id} href="javascript:;" class="del" >删除</a></span></th>
                       </tr>`;
      $(".layui-table tbody").append(arr);
    })
  })
};
load();

//添加表单数据
var arrstr = `  <form id="add-form" class="layui-form" style="margin: 15px 30px 0 0">
<!-- 第一行：密码 -->
<div class="layui-form-item">
  <label class="layui-form-label">链接名称</label>
  <div class="layui-input-block">
    <input type="text" name="linkname" required  lay-verify="required" placeholder="请输入链接名称" autocomplete="off" class="layui-input">
  </div>
</div>
<!-- 第二行：确认密码 -->
<div class="layui-form-item">
  <label class="layui-form-label">链接地址</label>
  <div class="layui-input-block">
    <input type="text" name="linkurl" required  lay-verify="required" placeholder="请输入链接地址" autocomplete="off" class="layui-input">
  </div>
</div>
<!-- 第三行：链接描述 -->
<div class="layui-form-item">
  <label class="layui-form-label">链接描述</label>
  <div class="layui-input-block">
    <input type="text" name="linkdesc" required  lay-verify="required" placeholder="请输入链接描述" autocomplete="off" class="layui-input">
  </div>
</div>
<!-- 第四行：上传图片 -->
<div class="layui-form-item">
  <div class="layui-input-block icon-url">
    <button type="button" class="layui-btn layui-btn-sm" id="urlIcon">
      <i class="layui-icon">&#xe67c;</i>上传图片
    </button>
    <input type="file" name="linkicon" id="linkFile" style="display: none;">
    <img id="preIcon" src="">
  </div>
</div>
<!-- 第三行：按钮 -->
<div class="layui-form-item">
  <div class="layui-input-block">
    <button class="layui-btn" lay-submit lay-filter="formDemo">提交</button>
    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
  </div>
</div>
</form>`;


//添加友情链接
$('#add-link').on('click', function () {
  var index = layer.open({
    type: 1,
    title: '添加友情链接',
    content: arrstr,
    area: ['500px', '350px']
  });
  $('#urlIcon').click(function () {
    $('#linkFile').click()
  })
  $('#linkFile').change(function (e) {
    const objURL = URL.createObjectURL(e.target.files[0])
    $('#preIcon').attr('src', objURL)
  });

  $('#add-form').on("submit", function (ev) {
    ev.preventDefault();
    let fd = new FormData(this)
    $.ajax({
      type: "POST",
      url: "http://localhost:8888/admin/links",
      data: fd,
      processData: false,
      contentType: false,
      beforeSend: function (xhr) {
        xhr.setRequestHeader("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiaWQiOjEsImlhdCI6MTYwODE3MDE3NSwiZXhwIjoxNjA4NjAyMTc1fQ.dTdbGwUoTl_NDBNK1KRnyfCtSy5ShDg4pBpl27Yre04");
      },
      success: function (res) {
        if (res.status === 0) {
          layer.close(index);
          load();
        }
      }
    })
  })


});

//删除链接
$('.tbody').on('click', ".del", function (ev) {
  // this 指向删除的a元素
  let id = $(this).data('id')
  axios({
    headers: {
      Authorization: sessionStorage.getItem('mytoken')
    },
    url: "http://localhost:8888/admin/links/" + id,
    method: "DELETE"
  }).then(res => {
    load();
  })
})

//编辑 表单数据   edit编辑（单词）
var editarr = `<form id="edit-form" lay-filter='editForm' class="layui-form" style="margin: 15px 30px 0 0">
<!-- 第一行：密码 -->
<div class="layui-form-item">
  <label class="layui-form-label">链接名称</label>
  <div class="layui-input-block">
    <input type="text" name="linkname" required  lay-verify="required" placeholder="请输入链接名称" autocomplete="off" class="layui-input">
  </div>
</div>
<!-- 第二行：确认密码 -->
<div class="layui-form-item">
  <label class="layui-form-label">链接地址</label>
  <div class="layui-input-block">
    <input type="text" name="linkurl" required  lay-verify="required" placeholder="请输入链接地址" autocomplete="off" class="layui-input">
  </div>
</div>
<!-- 第三行：链接描述 -->
<div class="layui-form-item">
  <label class="layui-form-label">链接描述</label>
  <div class="layui-input-block">
    <input type="text" name="linkdesc" required  lay-verify="required" placeholder="请输入链接描述" autocomplete="off" class="layui-input">
  </div>
</div>
<!-- 第四行：上传图片 -->
<div class="layui-form-item">
  <div class="layui-input-block icon-url">
    <button type="button" class="layui-btn layui-btn-sm" id="urlIcon">
      <i class="layui-icon">&#xe67c;</i>上传图片
    </button>
    <input type="file" id="linkFile" style="display: none;">
    <img id="preIcon" src="">
  </div>
</div>
<!-- 第三行：按钮 -->
<div class="layui-form-item">
  <div class="layui-input-block">
    <button class="layui-btn" lay-submit lay-filter="formDemo">提交</button>
    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
  </div>
</div>
</form>`;

//编辑友情链接
$(".layui-table tbody").on('click', '.bj', function (ev) {
  var id = $(ev.target).data('ide');
  $.ajax({
    url: 'http://localhost:8888/admin/links/' + id,
    type: "GET",
    beforeSend: function (xhr) {
      xhr.setRequestHeader("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiaWQiOjEsImlhdCI6MTYwODE3MDE3NSwiZXhwIjoxNjA4NjAyMTc1fQ.dTdbGwUoTl_NDBNK1KRnyfCtSy5ShDg4pBpl27Yre04");
    },
    success: function (res) {
      console.log(res)
      var index = layer.open({
        type: 1,
        title: '编辑友情链接',
        content: editarr,
        area: ['500px', '350px']
      })

      //console.log(res.data.linkicon);
      //$("#preIcon").attr('src', 'http://localhost:8888/uploads/' + res.data.linkicon);

      delete res.data.linkicon;
      form.val('editForm', res.data);

      $("#urlIcon").click(function () {
        $('#linkFile').click();
      });

      let file = null;
      $("#linkFile").change(function (ev) {
        const objurl = URL.createObjectURL(ev.target.files[0]);
        file = ev.target.files[0];
        $('#preIcon').attr('src', objurl);
      });

      $('#edit-form').submit(function (ev) {
        ev.preventDefault();
        let fd = new FormData(this);
        if (file) {
          fd.append('linkicon', file)
        }
        $.ajax({
          url: "http://localhost:8888/admin/links/" + id,
          type: "PUT",
          data: fd,
          processData: false,
          contentType: false,
          beforeSend: function (xhr) {
            xhr.setRequestHeader("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiaWQiOjEsImlhdCI6MTYwODE3MDE3NSwiZXhwIjoxNjA4NjAyMTc1fQ.dTdbGwUoTl_NDBNK1KRnyfCtSy5ShDg4pBpl27Yre04");
          },
          success: function (res) {
            if (res.status === 0) {
              layer.close(index);
              load();
            }
          }
        })
      })
    }
  });
})


